package com.jiaok.handler.security;

import cn.hutool.json.JSONUtil;
import com.jiaok.comm.CommonResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author jiaok
 * @Date 2023/5/10 11:21
 */
@Component
public class NonAuthorityHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        //将响应转换成流的形式
        ServletOutputStream outputStream = response.getOutputStream();

        CommonResponse result = new CommonResponse(403,"无权限访问");
        //将结果按照流的形式输出_且按照json格式
        outputStream.write(JSONUtil.toJsonStr(result).getBytes("UtF-8"));

        //将流输出
        outputStream.flush();
        //关闭流
        outputStream.close();

    }
}
